package com.chu.cloud.service.impl;

import com.chu.cloud.entity.Address;
import com.chu.cloud.repository.AddressRepository;
import com.chu.cloud.util.ChuException;
import com.chu.cloud.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/4/16 15:02
 * @Description:
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class AddressService {

    @Autowired
    private AddressRepository addressRepository;

    public Integer save(Address address) {
        if (address.isDefaultAddress()){
            addressRepository.clearDefaultAddress(address.getUserId());
        }
        Address result = addressRepository.save(address);
        log.debug("register address successfully. {}", JsonUtils.obj2json(result));
        return result.getId();
    }


    public Address findAddressId(Integer id) {
        Address address = Optional.of(addressRepository.findOne(id))
                                  .orElseThrow(() -> new ChuException("记录不存在"));
        return address;
    }

    public Address findDefault(Integer userId) {
        Address address = Optional.ofNullable(addressRepository.findByUserIdAndDefaultAddress(userId, true))
                                  .orElseThrow(() -> new ChuException("记录不存在"));
        return address;
    }
}
